package edu.friday.controller;


import edu.friday.common.result.RestResult;
import edu.friday.common.security.LoginUser;
import edu.friday.common.security.service.SysLoginService;
import edu.friday.common.security.service.SysPermissionService;
import edu.friday.common.security.service.TokenService;
import edu.friday.model.vo.SysMenuVO;
import edu.friday.model.vo.SysUserVO;
import edu.friday.service.ISysMenuService;
import edu.friday.utils.StringUtils;
import edu.friday.utils.http.ServletUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Set;

/**
 * 登录验证
 */
@RestController
public class SysLoginController {

    @Autowired
    private SysLoginService sysLoginService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private SysPermissionService sysPermissionService;

    @Autowired
    private ISysMenuService iSysMenuService;

    @PostMapping({"/login", "/"})
    public RestResult login(String username, String password, String uuid) {
        System.out.println("/login: username[" + username + "]" + "password: [" + password + "]" + "uuid: [" + uuid + "]");
        String token = sysLoginService.login(username, password, uuid);
        if (StringUtils.isEmpty(token))
            return RestResult.error("token获取失败");
        return RestResult.success("操作成功", token);
    }

    @GetMapping("/getInfo")
    public RestResult getInfo() {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        SysUserVO user = loginUser.getUser();
        Set<String> permission = sysPermissionService.selectMenuPermission(user);
        Set<String> roles = sysPermissionService.selectRolePermission(user);
        RestResult success = RestResult.success();
        success.put("permissions", permission);
        success.put("roles", roles);
        success.put("user", user);
        return success;
    }

    @GetMapping("/getRouters")
    public RestResult getRouters() {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        // 用户信息
        SysUserVO user = loginUser.getUser();
        List<SysMenuVO> menus = iSysMenuService.selectMenuTreeByUserId(user.getUserId());
        return RestResult.success(iSysMenuService.buildMenus(menus));
    }
}
